package com.ocean.linkedlist;

/**
 * https://leetcode.cn/problems/reverse-linked-list/
 */
public class ReverseList4 {
    public static void main(String[] args) {
//        head = [1,2,3,4,5]
        ListNode e5 = new ListNode(5, null);
        ListNode e4 = new ListNode(4, e5);
        ListNode e3 = new ListNode(3, e4);
        ListNode e2 = new ListNode(2, e3);
        ListNode e1 = new ListNode(1, e2);
        ReverseList4 reverseList = new ReverseList4();
        reverseList.print(e1);
        ListNode listNode = reverseList.reverseList(e1);
        reverseList.print(listNode);

    }

    public ListNode reverseList(ListNode head) {
        ListNode cur = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = cur;
            cur = head;
            head = next;
        }
        return cur;
    }


    private void print(ListNode head) {
        StringBuilder builder = new StringBuilder();
        builder.append(head.val + ",");
        ListNode temp = head;
        while (temp.next != null) {
            temp = temp.next;
            builder.append(temp.val);
            if (temp.next != null) {
                builder.append(",");
            }
        }
        System.out.println(builder);
    }


}
